package net.huashitong.ssydt.provider.security.interceptor;


import net.huashitong.ssydt.provider.annotations.LoginRequired;
import net.huashitong.ssydt.provider.security.exceptions.LoginElsewhereException;
import net.huashitong.ssydt.provider.security.exceptions.LoginoutException;
import net.huashitong.ssydt.provider.security.exceptions.OvertimeException;
import net.huashitong.ssydt.provider.security.exceptions.ParamErrorException;
import net.huashitong.ssydt.provider.utils.StringUtils;
import net.huashitong.ssydt.provider.web.model.Result;
import net.huashitong.ssydt.security.utils.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 需要登录拦截
 *
 * @author huiyang.yu
 */
public class AuthenticationInterceptor extends ValidatorInterceptor {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected boolean validate(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        if (methodAnnotation != null) {
            if (StringUtils.isBlank(UserUtils.getUserId())) {
                switch (UserUtils.getUserSession().get().getErrorCode()) {
                    case Result.Status.PARAM_ERROR:
                        throw new ParamErrorException(UserUtils.getUserSession().get().getErrorMessage());
                    case Result.Status.OVERTIME:
                        throw new OvertimeException(UserUtils.getUserSession().get().getErrorMessage());
                    case Result.Status.LOGINOUT:
                        throw new LoginoutException(UserUtils.getUserSession().get().getErrorMessage());
                    case Result.Status.LOGIN_ELSEWHERE:
                        throw new LoginElsewhereException(UserUtils.getUserSession().get().getErrorMessage());
                    default:

                }
            }
            return true;
        }

        return true;
    }
}
